/*
 * Created on Jan 1, 2008
 * 
 * By Erick Audet for OTN
 *
 * Copyright (c) 2008 Oracle Corporation. All Rights Reserved.
 *
 *
 */

package com.sample.services;

import com.sample.accessors.UserAccessor;
import com.sample.entities.User;
import com.sleepycat.je.DatabaseException;

/**
 * This class act has a service layer (facade/session bean) on top of entities/model classes. 
 * This will keep all the business logic here at on place.
 * 
 * @author eaudet
 *
 */

public class UserService extends BaseService {
	
	
	UserAccessor userAccessor;

	/**
	 * Creates a user but first checks if all mandatory fields are there
	 */
	public User createUser( User pUser ) throws DatabaseException, Exception{
		
		UserAccessor wUserAccessor = new UserAccessor();
		
		//check mandatory fields
		if ( pUser.getFirstName().equals("") ||
				pUser.getLastName().equals("") ||
				pUser.getUserName().equals("") ){
			throw new Exception("Missing madatory fields");
		}
		
		
		open( false, wUserAccessor);
	
		// Start a transaction.
		startTransaction();
	
		// Put it in the store. Note that this causes our secondary key
		// to be automatically updated for us.
		try {
			
			wUserAccessor.userByUserName.put( pUser );
			
			// Commit the transaction. The data is now safely written to the
			// store.
			commit();
			
		} catch (DatabaseException dbe) {
			try {
				System.out.println("Error creating a user");
			} catch (Exception willNeverOccur) {
			}
			txn.abort();
			throw dbe;
		} catch (Exception e) {
			txn.abort();
			e.printStackTrace();
		}
		
		return pUser;
	}
	

		
		
}
